package com.jy.unkown.view;


import android.content.Context;

import android.media.MediaPlayer;

import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;

import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amjy.dsl.R;
import com.bumptech.glide.Glide;
import com.jiayou.ziyou_ad.utils.MD5Util;
import com.jy.unkown.UnkownVideoPoint2;
import com.jy.unkown.entity.UnkownAdBean;
import com.jy.utils.cache.SpManager;
import com.jy.utils.utils.ApkUtils;
import com.jy.utils.utils.UI;

import java.io.File;
import java.util.List;

public class UnkownBannerView extends UnkownADView implements View.OnClickListener {


    public UnkownBannerView(@NonNull Context context) {
        super(context);
    }

    public UnkownBannerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public UnkownBannerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    TextView progressText;
    UnkowVideoView unkowVideoView;
    UnkownVideoPoint2 unkownVideoPoint2;

    @Override
    public void show() {
        setTAG("banner广告");
        if (baseUnkownAd == null) {
            err();
            return;
        }
        try {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_banner_view, null);
            UnkownAdBean unkownAdBean = baseUnkownAd;
            String adlogo = unkownAdBean.adlogo;
            ImageView logoImg = view.findViewById(R.id.native_baidulogo);
//            Glide.with(getContext()).load(adlogo).into(logoImg);

            logoImg.setVisibility(GONE);
            view.findViewById(R.id.adclose).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ViewGroup viewGroup = (ViewGroup) UnkownBannerView.this.getParent();
                    if (viewGroup != null) {
                        viewGroup.removeView(UnkownBannerView.this);
                        onDestory();
                        adClose();
                    }
                }
            });


            progressText = view.findViewById(R.id.progressText);
            ImageView native_main_image = view.findViewById(R.id.native_main_image);
            TextView native_text = view.findViewById(R.id.native_text);
            native_text.setText(unkownAdBean.adtext);

            if (unkownAdBean.metaGroup != null && unkownAdBean.metaGroup.size() > 0) {
                UnkownAdBean.MetaGroupDTO metaGroupDTO = unkownAdBean.metaGroup.get(0);
                List<String> descs = metaGroupDTO.descs;
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < descs.size(); i++) {
                    stringBuffer.append(descs.get(i)).append("\n");
                }
                native_text.setText(stringBuffer.toString());
                TextView native_brand_name = view.findViewById(R.id.native_brand_name);
                native_brand_name.setText(metaGroupDTO.brandName);
                if (metaGroupDTO.creativeType == 1) {
                    //文字
                    view.findViewById(R.id.ghost_vi).setVisibility(GONE);
                } else if (metaGroupDTO.creativeType == 2) {

                    List<String> images = metaGroupDTO.imageUrl;
                    if (images != null && images.size() > 0) {
                        Glide.with(getContext()).load(images.get(0)).into(native_main_image);
                    }
                } else if (metaGroupDTO.creativeType == 5) {
                    ViewStub viewStub = view.findViewById(R.id.videoStub);
                    View vv = viewStub.inflate();
                    unkowVideoView = vv.findViewById(R.id.unkownVideoView);
                    unkowVideoView.setUrl(metaGroupDTO.videoUrl);

                    List<String> images = metaGroupDTO.imageUrl;
                    if (images != null && images.size() > 0) {
                        Glide.with(getContext()).load(images.get(0)).into(native_main_image);
                    }

                    unkowVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            try {
                                if (metaGroupDTO != null) {
                                    List<String> winloadUrls = metaGroupDTO.winLoadUrls;
                                    pointPost(UnkownADView.PLAY_VIDEO, "winloadUrls 视频加载成功", winloadUrls);
                                    native_main_image.setVisibility(GONE);
                                }
                            } catch (Exception exception) {

                            }

                        }
                    });
                    unkownVideoPoint2 = new UnkownVideoPoint2(this, unkowVideoView, unkownAdBean.tracks);
                    unkownVideoPoint2.init();
                    UI.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            unkowVideoView.playVideo();
                        }
                    }, 1000);
                }


                if (metaGroupDTO.interactionType == 3) {//进入下载页面
                    progressText.setText("详情");
                } else if (metaGroupDTO.interactionType == 2) {//下载类
                    boolean isInstall = ApkUtils.isInstall(metaGroupDTO.packageName);
                    if (isInstall) {
                        progressText.setText("打开");
                    } else {
                        if (metaGroupDTO != null) {
                            String downUrl = metaGroupDTO.clickUrl;
                            String key = MD5Util.getMD5(downUrl);
                            String path = SpManager.getString(key, "");
                            if (TextUtils.isEmpty(path)) {
                                progressText.setText("下载");
                            } else {
                                if (ApkUtils.checkApkFileIsVaild(path)) {
                                    progressText.setText("安装");
                                } else {
                                    progressText.setText("下载");
                                }
                            }
                        }
                    }

                    native_brand_name.setText(metaGroupDTO.brandName);

                } else if (metaGroupDTO.interactionType == 1) {//跳转类
                    progressText.setText("详情");
                }
            }
            LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            addView(view, layoutParams);
            setOnClickListener(this);
            UnkownAdBean.MetaGroupDTO metaGroupDTO = getMetaGroupDTOBean();
            if (metaGroupDTO != null) {
                exposure(metaGroupDTO.winNoticeUrls);
            }
        } catch (Exception exception) {
            err();
        }

    }


    boolean isAttachedToWindow = false;

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        isAttachedToWindow = true;
        if (unkowVideoView != null) {
            unkowVideoView.playVideo();
        }
        Log.e(getClass().getSimpleName(), "onAttachedToWindow");
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isAttachedToWindow = false;
        if (unkowVideoView != null) {
            unkowVideoView.onPause();
        }
        Log.e(getClass().getSimpleName(), "onDetachedFromWindow");
    }


    @Override
    void downloadSucc(String url, File progress) {
        if (progressText != null && isAttachedToWindow) {
            UI.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("下载完成");
                }
            });
        }
    }

    @Override
    void downloadErr(String url, Exception e) {
        if (progressText != null && isAttachedToWindow) {
            UI.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("下载失败");
                }
            });
        }
    }

    @Override
    void downloadProgress(String url, int progress) {
        if (progressText != null && isAttachedToWindow) {
            UI.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("下载" + progress + "%");
                }
            });
        }
    }

    public void onDestory() {
        try {
            unkownVideoPoint2.setStart(false);
            unkowVideoView.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
